package com.xbongbong.workflow.service.strategy.data.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.log.constant.CrmLogMemoConstant;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.service.CustomerRuleService;
import com.xbongbong.paas.service.TransferBackRuleScriptService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.customercommunicate.pojo.dto.CustomerDynamicAddDTO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.CommuicatePlanErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.message.constant.CommunicatePushConstant;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.help.PushHelper;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.message.service.MessageService;
import com.xbongbong.pro.score.pojo.dto.DataScoreUpdateSingleDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ext.ClueEntityExt;
import com.xbongbong.saas.domain.entity.ext.CommunicatePlanEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerCommunicateEntityExt;
import com.xbongbong.saas.enums.ClueRuleSettingEnum;
import com.xbongbong.saas.enums.ExecutorCheckBoxEnum;
import com.xbongbong.saas.enums.ProjectLogEnum;
import com.xbongbong.saas.enums.RuleSettingEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.base.CommunicateBaseEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CommunicatePlanEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.dictionary.ClueStatusEnum;
import com.xbongbong.saas.enums.dictionary.CommunicatePlanStatusEnum;
import com.xbongbong.saas.model.ClueModel;
import com.xbongbong.saas.model.CommunicatePlanModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.OpportunityModel;
import com.xbongbong.saas.service.CustomerCommunicateService;
import com.xbongbong.saas.service.ListBatchService;
import com.xbongbong.saas.service.ScoreCalculateService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.User;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy;
import com.xbongbong.workflow.service.strategy.data.WorkflowDataProcessStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getIntegerOrDefaultFromFormData;

/**
 *
 * @author 魏荣杰
 *
 */
@Service
@Slf4j
public class WorkflowCommunicateStrategy extends AbstractWorkflowDataStrategy implements WorkflowDataProcessStrategy {

    @Resource
    private CustomerModel customerModel;
    @Resource
    private UserModel userModel;
    @Resource
    private ClueModel clueModel;
    @Resource
    private CommunicatePlanModel communicatePlanModel;
    @Resource
    private PushHelper pushHelper;
    @Resource
    private OpportunityModel opportunityModel;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private CustomerRuleService customerRuleService;
    @Resource
    private MessageService messageService;
    @Resource
    private ListBatchService listBatchService;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private ScoreCalculateService scoreCalculateService;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private CustomerCommunicateService customerCommunicateService;
    @Resource
    private TransferBackRuleScriptService transferBackRuleScriptService;


    @Override
    public List<Integer> type() {
        return Collections.singletonList(XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode());
    }

    @Override
    public void save(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {

        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        Data pojoData = workflowTransferPOJO.getData();
        JSONObject data = pojoData.getData();
        Long dataId = pojoData.getId();
        String corpid = workflowTransferPOJO.getCorpid();
        User user = workflowTransferPOJO.getUser();
        String userId = user.getUserId();
        UserEntity userEntity = userModel.getByKeyIngoreDel(userId, corpid);
        Long communicateTime = FastJsonHelper.getLongFromFormData(data, CustomerCommunicateEnum.COMMUNICATE_TIME.getAttr());
        Long customerId = FastJsonHelper.getLongFromFormData(data, CustomerCommunicateEnum.CUSTOMER_NAME.getAttr());
        String customerName = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerCommunicateEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), "");
        List<Long> contactIds = FastJsonHelper.getTransferTypesFromData(data, CustomerCommunicateEnum.CONTACT_ARRAY.getAttr(), Long.class);

        PaasFormDataEntityExt customerEntityExt = customerModel.getByKey(customerId,corpid);
        boolean clueDetailAddOrSaveClue = false;
        Integer communicateBusinessType = getIntegerOrDefaultFromFormData(data, CustomerCommunicateEnum.COMMUNICATE_BUSINESS_TYPE.getAttr(), BasicConstant.ZERO);
        boolean isClue = Objects.equals(communicateBusinessType, XbbRefTypeEnum.CLUE.getCode());
        if ((Objects.nonNull(saasNeedRedundantAttrPojo) && Objects.equals(saasNeedRedundantAttrPojo.getParentBusinessType(), XbbRefTypeEnum.CLUE.getCode())) || Objects.equals(communicateBusinessType, XbbRefTypeEnum.CLUE.getCode())) {
            // 线索关联新建或者是保存跟进业务是线索的时候，不校验关联客户，因为他不展示展示这个字段
            clueDetailAddOrSaveClue = true;
        }
        JSONObject customerData = null;
        if (!clueDetailAddOrSaveClue) {
            customerData = customerEntityExt.getData();
        }
        Integer ifRemind = getIntegerOrDefaultFromFormData(data, CustomerCommunicateEnum.IF_REMIND.getAttr(), BasicConstant.ZERO);
        Integer isPlan = getIntegerOrDefaultFromFormData(data, CustomerCommunicateEnum.ENTER_COMMUNICATE_PLAN.getAttr(), BasicConstant.ZERO);
        if (isClue){
            Long clueId = FastJsonHelper.getLongFromFormData(data, CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getAttr());
            ClueEntityExt clueEntity = clueModel.getByKey(clueId, corpid);
            if (Objects.nonNull(clueEntity)) {
                Map<String, Object> clueParams = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                String status = FastJsonHelper.getStringOrDefaultFromFormData(clueEntity.getData(), ClueEnum.CLUE_STATUS.getAttr(), "");
                if (Objects.equals(status, ClueStatusEnum.PENDING.getCode())) {
                    // 只有线索状态为【未跟进】时填写跟进记录后销售线索线索状态变为【跟进中】
                    clueParams.put(ClueEnum.CLUE_STATUS.getAttr(), ClueStatusEnum.FOLLOWING_UP.getCode());
                }
                Boolean flag = proFormHelp.getClueSingleRuleList(corpid, ClueRuleSettingEnum.NEW_FOLLOW_UP_RECORD_VISITING_TIME.getConfig(), clueEntity.getFormId());
                if (flag) {
                    Long clueLastConnectTime = FastJsonHelper.getLongOrDefaultFromFormData(clueEntity.getData(), ClueEnum.LAST_CONNECT_TIME.getAttr(), 0L);
                    if (communicateTime > clueLastConnectTime) {
                        clueParams.put(ClueEnum.LAST_CONNECT_TIME.getAttr(), communicateTime);
                        if (commonHelp.isCustomerPublicPoolSeniorModel(corpid)) {
                            transferBackRuleScriptService.deletePublicSeniorTag(corpid, Collections.singletonList(clueId), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), customerEntityExt.getFormId());
                        } else {
                            customerRuleService.deletePublicTag(corpid, Collections.singletonList(clueId));
                        }
                    }
                }
                if (!clueParams.isEmpty()) {
                    clueModel.jsonsetNoSubById(corpid, clueId, clueParams);
                    //线索的跟进记录存在客户这边
                    //评分更新（线索新增跟进记录，修改了线索的“最后跟进时间”）这里要取的是 clueId,因为 clueModel.jsonsetNoSubById 对线索进行了更新，直接取clueEntity是不准的。
//                    scoreCalculateService.asyncUpdateSingleDataScore(XbbRefTypeEnum.CLUE,corpid,clueId,null);
                    DataScoreUpdateSingleDTO dataScoreUpdateBatchDTO = new DataScoreUpdateSingleDTO();
                    dataScoreUpdateBatchDTO.setCorpid(corpid);
                    dataScoreUpdateBatchDTO.setUserId(workflowTransferPOJO.getUser().getUserId());
                    dataScoreUpdateBatchDTO.setBusinessType(XbbRefTypeEnum.CLUE.getCode());
                    dataScoreUpdateBatchDTO.setDataId(clueId);
                    dataScoreUpdateBatchDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                    scoreCalculateService.updateSingle(dataScoreUpdateBatchDTO);
                }
            }

        }else {
            try {
                if (isNotDistributeBusinessType(workflowTransferPOJO)) {
                    CustomerDynamicAddDTO customerDynamicAddDTO = new CustomerDynamicAddDTO();
                    customerDynamicAddDTO.setCorpid(corpid);
                    customerDynamicAddDTO.setUserId(user.getUserId());

                    String memo = Objects.equals(workflowTransferPOJO.getIsImport(), BasicConstant.ONE) ? CrmLogMemoConstant.DYNAMIC_USER_COMMUNICATE_IMPORT : CrmLogMemoConstant.DYNAMIC_USER_COMMUNICATE_ADD;
                    customerDynamicAddDTO.setMemo(String.format(I18nMessageUtil.getMessage(memo), userEntity.getName()));
                    customerDynamicAddDTO.setCustomerId(customerId);
                    customerDynamicAddDTO.setContactIds(contactIds);

                    // 关联业务
                    Long refTypeId = FastJsonHelper.getLongFromFormData(data, CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getAttr());
                    if (Objects.nonNull(refTypeId)) {
                        XbbRefTypeEnum communicateType = XbbRefTypeEnum.getByCode(communicateBusinessType);
                        switch (communicateType) {
                            case SALES_OPPORTUNITY:
                                customerDynamicAddDTO.setOpportunityIds(Collections.singletonList(refTypeId));
                                break;
                            case CONTRACT:
                                customerDynamicAddDTO.setContractIds(Collections.singletonList(refTypeId));
                                break;
                        }
                    }

                    customerDynamicAddDTO.setCustomerName(customerName);
                    customerDynamicAddDTO.setDataId(dataId);
                    customerDynamicAddDTO.setCommunicateBusinessType(XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode());

                    String communicateInfo = data.getString(CommunicateBaseEnum.MEMO.getAttr());
                    customerDynamicAddDTO.setCommunicateBusinessText(communicateInfo);

                    customerDynamicAddDTO.setLogType(ProjectLogEnum.CUSTOMER_COMMUNICATE_CREATE.getSubType());
                    customerDynamicAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                    customerCommunicateService.addCustomerDynamic(customerDynamicAddDTO);
                }
            } catch (Exception e) {
                log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowCommunicateStrategy.save", e);
            }
        }
        //同步完成访客计划
        Long communicatePlanId = 0L;
        try {
            communicatePlanId = data.getLong(CustomerCommunicateEnum.FINISH_COMMUNICATE_PLAN_ID.getAttr());
            if (communicatePlanId == null) {
                communicatePlanId = 0L;
            }
        } catch (Exception e) {
            communicatePlanId = 0L;
        }
        if (communicatePlanId > 0) {
            CommunicatePlanEntityExt planEntityExt = communicatePlanModel.getByKey(communicatePlanId, corpid);
            if (Objects.isNull(planEntityExt)) {
                throw new XbbException(CommuicatePlanErrorCodeEnum.API_ERROR_214011);
            }
            Long planCustomerId = FastJsonHelper.getLongOrDefaultFromFormData(planEntityExt.getData(), CommunicatePlanEnum.LINK_CUSTOMER.getAttr(), 0L);
            if (!Objects.equals(planCustomerId, customerId)) {
                throw new XbbException(CommuicatePlanErrorCodeEnum.API_ERROR_214010);
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(CommunicatePlanEnum.FINISH_USER_ID.getAttr(), userEntity.getUserId());
            jsonObject.put(CommunicatePlanEnum.FINISH_USER_AVATAR.getAttr(), userEntity.getAvatar());
            jsonObject.put(CommunicatePlanEnum.FINISH_USER_NAME.getAttr(), userEntity.getName());
            jsonObject.put(CommunicatePlanEnum.FINISH_TIME.getAttr(), DateUtil.getInt());
            jsonObject.put(CommunicatePlanEnum.STATUS.getAttr(), CommunicatePlanStatusEnum.FINISH.getCode());
            UpdateDataEntity updateData = ExplainUtil.getUpdateData(communicatePlanId, jsonObject, corpid);
            communicatePlanModel.updateBatch(Collections.singletonList(updateData), corpid);
        }

        if (Objects.equals(ifRemind, BasicConstant.ONE) && !clueDetailAddOrSaveClue) {
            // 下次跟进提醒保存
            PushRefTypePojo.Options options = new PushRefTypePojo.Options(pojoData.getAppId(), pojoData.getMenuId(), pojoData.getFormId(), dataId, SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
            Long notifyTime = FastJsonHelper.getLongOrDefaultFromFormData(data, CustomerCommunicateEnum.NOTIFY_TIME.getAttr(), 0L);
            String content = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerCommunicateEnum.NEXT_NOTIFY_MEMO.getAttr(), "");
            MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, Collections.singletonList(userId), Collections.singletonList(dataId), 1, notifyTime, XbbRefTypeEnum.PUSH_NOTIFY.getName(), content, null, options);
            messageService.insertPushData(messageRabbitMqDTO, PushTypeEnum.CUSTOMER_PUSH);


            if(Objects.equals(isPlan, BasicConstant.ONE)){

                // 加入访客计划
                JSONArray customerArr = new JSONArray();
                JSONObject customerObj = new JSONObject();
                customerObj.put(StringConstant.SAAS_LINK_BUSINESS_ID, FastJsonHelper.getLongOrDefaultFromFormData(data, CustomerCommunicateEnum.CUSTOMER_NAME.getAttr(), 0L));
                customerObj.put(StringConstant.SAAS_LINK_BUSINESS_NAME, FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerCommunicateEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), ""));
                customerArr.add(customerObj);
                Long nextCommunicateTime = FastJsonHelper.getLongOrDefaultFromFormData(data, CustomerCommunicateEnum.NEXT_COMMUNICATE_TIME.getAttr(), 0L);
                String notifyTypeMemo = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerCommunicateEnum.NEXT_NOTIFY_MEMO.getAttr(), "");
                JSONObject planDataList = new JSONObject();

                FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
                PaasFormExplainEntity planExplain = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.COMMUNICATE_PLAN.getCode(), corpid);
                BeanUtil.copyProperties(planExplain, formDataAddDTO);
                planDataList.put(CommunicatePlanEnum.LINK_CUSTOMER.getAttr(), customerArr);
                planDataList.put(CommunicatePlanEnum.EXECUTOR.getAttr(), Collections.singletonList(ExecutorCheckBoxEnum.CUSTOM_CHECK.getCode()));
                JSONObject executorObj = new JSONObject();
                executorObj.put(StringConstant.SAAS_LINK_BUSINESS_ID, userId);
                JSONArray executorArr = new JSONArray();
                executorArr.add(executorObj);
                planDataList.put(CommunicatePlanEnum.EXECUTOR_LINKED_TEXT.getAttr(), executorArr);
                planDataList.put(CommunicatePlanEnum.TARGET.getAttr(), "");
                planDataList.put(CommunicatePlanEnum.COMMUNICATE_TIME.getAttr(), nextCommunicateTime);
                planDataList.put(CommunicatePlanEnum.NOTIFY_TYPE.getAttr(), getIntegerOrDefaultFromFormData(data, CustomerCommunicateEnum.NOTIFY_TYPE.getAttr(), 0));
                planDataList.put(CommunicatePlanEnum.NOTIFY_TIME.getAttr(), getIntegerOrDefaultFromFormData(data, CustomerCommunicateEnum.NOTIFY_TIME.getAttr(), BasicConstant.ZERO));
                planDataList.put(CommunicatePlanEnum.MEMO.getAttr(), notifyTypeMemo);
                formDataAddDTO.setDataList(planDataList);
                formDataAddDTO.setSerialNo("");
                formDataAddDTO.setUserId(userId);
                formDataAddDTO.setCorpid(corpid);
                formDataAddDTO.setBusinessType(XbbRefTypeEnum.COMMUNICATE_PLAN.getCode());
                UserVO userVO = new UserVO();
                BeanUtil.copyProperties(userEntity, userVO);
                formDataAddDTO.setLoginUser(userVO);
                formDataAddDTO.setUserId(userId);
                formDataAddDTO.setLoginUserName(user.getName());
                formDataAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());

                listBatchService.joinCommunicatePlan(formDataAddDTO);
            }
        }
        if (!Objects.equals(workflowTransferPOJO.getIsImport(), 1)) {
            String creatorId = user.getUserId();
            UserEntity creator;
            if (StringUtil.isNotEmpty(creatorId)) {
                creator = userModel.getByKey(creatorId, corpid);
            } else {
                creator = userEntity;
            }
            // 跟进记录新建消息推送
            CustomerCommunicateEntityExt customerCommunicateEntityExt = new CustomerCommunicateEntityExt();
            customerCommunicateEntityExt.setId(dataId);
            customerCommunicateEntityExt.setData(data);
            List<String> pushUserList = pushHelper.getUserIdListByPushSetRule(corpid, PushTypeEnum.COMMUNICATE_ADD_PUSH.getCode(), PushTypeEnum.COMMUNICATE_ADD_PUSH.getSubCode(), creator,  customerCommunicateEntityExt);
            PushRefTypePojo.Options options = new PushRefTypePojo.Options(pojoData.getAppId(), pojoData.getMenuId(), pojoData.getFormId(), dataId, Collections.singletonList(dataId), SaasMarkEnum.SAAS.getCode(), pojoData.getBusinessType(), pojoData.getSubBusinessType());
            String content = String.format(I18nMessageUtil.getMessage(CommunicatePushConstant.COMMUNICATE_ADD_CONTENT), creator.getName(), customerName);
            if (isClue) {
                customerName = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerCommunicateEnum.COMMUNICATE_BUSINESS_LINK_TEXT.getAttr(), "");
                content = String.format(I18nMessageUtil.getMessage(CommunicatePushConstant.COMMUNICATE_ADD_CONTENT_CLUE), user.getName(), customerName);
            }
            MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, pushUserList, Collections.singletonList(dataId), 0, null, I18nMessageUtil.getMessage(CommunicatePushConstant.COMMUNICATE_ADD_TITLE), content, null, options);
            messageService.delayPushDingtalkOAMessage(messageRabbitMqDTO, PushTypeEnum.COMMUNICATE_ADD_PUSH);
        }


        // 新建跟进记录中@指定人员
        List<String> atUserIds = saasNeedRedundantAttrPojo.getAtUserIds();
        if (Objects.isNull(atUserIds)) {
            JSONArray jsonArray = data.getJSONArray(CustomerCommunicateEnum.AT_USERNAME.getAttr());
            if (Objects.nonNull(jsonArray)) {
                atUserIds = JSONArray.parseArray(jsonArray.toJSONString(),String.class);
            }
        }
        if (Objects.nonNull(atUserIds) && atUserIds.size() > 0) {
            atUserIds.remove(userId);
            String pushTitle = I18nMessageUtil.getMessage(CommunicatePushConstant.COMMUNICATE_AT_TITLE);
            String customerNameStr;
            String pushContent;
            if (isClue) {
                customerNameStr = FastJsonHelper.getStringOrDefaultFromFormData(data, CommunicateBaseEnum.COMMUNICATE_BUSINESS_HIDE.getAttr(), "");
                pushContent = String.format(I18nMessageUtil.getMessage(CommunicatePushConstant.COMMUNICATE_AT_CONTENT_CLUE), user.getName(), customerNameStr);
            } else {
                customerNameStr = FastJsonHelper.getStringOrDefaultFromFormData(data, CommunicateBaseEnum.MAIN_BUSINESS_HIDE.getAttr(), "");
                pushContent = String.format(I18nMessageUtil.getMessage(CommunicatePushConstant.COMMUNICATE_AT_CONTENT), user.getName(), customerNameStr);
            }
            PushTypeEnum pushTypeEnum = PushTypeEnum.COMMUNICATE_ADD_PUSH;

            PushRefTypePojo.Options options = new PushRefTypePojo.Options(pojoData.getAppId(), pojoData.getMenuId(), pojoData.getFormId(), dataId, Collections.singletonList(dataId), SaasMarkEnum.SAAS.getCode(), pojoData.getBusinessType(), pojoData.getSubBusinessType());
            MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, atUserIds, Collections.singletonList(dataId), 0, null, pushTitle, pushContent, null, options);
            messageService.delayPushDingtalkOAMessage(messageRabbitMqDTO, pushTypeEnum);
        }

        Integer businessType = getIntegerOrDefaultFromFormData(data, CustomerCommunicateEnum.COMMUNICATE_BUSINESS_TYPE.getAttr(), BasicConstant.ZERO);
        if (Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())) {
            Long opportunityId = FastJsonHelper.getLongOrDefaultFromFormData(data, CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getAttr(), 0L);
            if (!Objects.equals(opportunityId, 0L)) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(SalesOpportunityEnum.LAST_CONNECT_TIME.getAttr(), communicateTime);
                UpdateDataEntity updateData = ExplainUtil.getUpdateData(opportunityId, jsonObject, corpid);
                opportunityModel.updateBatch(Collections.singletonList(updateData), corpid);
            }
        }


        JSONObject jsonObject = new JSONObject();
        if (!clueDetailAddOrSaveClue && customerData.getLong(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr()) < communicateTime){
            if (communicateTime > DateTimeUtil.getInt()) {
                communicateTime = DateTimeUtil.getInt();
            }
            Boolean flag = proFormHelp.getSingleRuleList(corpid, RuleSettingEnum.NEW_FOLLOW_UP_RECORD_VISITING_TIME.getConfig(), customerEntityExt.getFormId());
            if (flag) {
                jsonObject.put(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), communicateTime);
            }

        }
        if (jsonObject.size() > 0) {
            UpdateDataEntity updateData = ExplainUtil.getUpdateData(customerId, jsonObject, corpid);
            customerModel.updateBatch(Collections.singletonList(updateData), corpid);

            Long communicateCustomerId = FastJsonHelper.getLongFromFormData(data, CustomerCommunicateEnum.CUSTOMER_NAME.getAttr());
        if (commonHelp.isCustomerPublicPoolSeniorModel(corpid)){
            transferBackRuleScriptService.deletePublicSeniorTag(corpid, Collections.singletonList(communicateCustomerId), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), customerEntityExt.getFormId());
        }else {
            customerRuleService.deletePublicTag(corpid, Collections.singletonList(communicateCustomerId));
        }
            //评分计算（客户新增，跟进记录）
            DataScoreUpdateSingleDTO dataScoreUpdateBatchDTO = new DataScoreUpdateSingleDTO();
            dataScoreUpdateBatchDTO.setCorpid(corpid);
            dataScoreUpdateBatchDTO.setUserId(workflowTransferPOJO.getUser().getUserId());
            dataScoreUpdateBatchDTO.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
            dataScoreUpdateBatchDTO.setDataId(customerId);
            dataScoreUpdateBatchDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
            scoreCalculateService.updateSingle(dataScoreUpdateBatchDTO);
//            scoreCalculateService.asyncUpdateSingleDataScore(XbbRefTypeEnum.CUSTOMER_MANAGEMENT,corpid,customerId,null);
        }

        addLinkDataDynamic(workflowTransferPOJO);
        // api
        apiHook(workflowTransferPOJO);
        // log
        afterSaveLog(workflowTransferPOJO);
    }

    @Override
    public void update(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        String corpid = workflowTransferPOJO.getCorpid();
        Data pojoData = workflowTransferPOJO.getData();
        JSONObject data = pojoData.getData();
        Long dataId = pojoData.getId();
        User user = workflowTransferPOJO.getUser();
        String userId = user.getUserId();
        UserEntity userEntity = userModel.getByKeyIngoreDel(userId, corpid);

        Long communicateTime = FastJsonHelper.getLongFromFormData(data, CustomerCommunicateEnum.COMMUNICATE_TIME.getAttr());
        Long customerId = FastJsonHelper.getLongFromFormData(data, CustomerCommunicateEnum.CUSTOMER_NAME.getAttr());
        String customerName = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerCommunicateEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), "");

        PaasFormDataEntityExt customerEntityExt = customerModel.getByKey(customerId,corpid);
        boolean clueDetailAddOrSaveClue = false;
        Integer communicateBusinessType = getIntegerOrDefaultFromFormData(data, CustomerCommunicateEnum.COMMUNICATE_BUSINESS_TYPE.getAttr(), BasicConstant.ZERO);
        boolean isClue = Objects.equals(communicateBusinessType, XbbRefTypeEnum.CLUE.getCode());
        if ((Objects.nonNull(saasNeedRedundantAttrPojo) && Objects.equals(saasNeedRedundantAttrPojo.getParentBusinessType(), XbbRefTypeEnum.CLUE.getCode())) || Objects.equals(communicateBusinessType, XbbRefTypeEnum.CLUE.getCode())) {
            // 线索关联新建或者是保存跟进业务是线索的时候，不校验关联客户，因为他不展示展示这个字段
            clueDetailAddOrSaveClue = true;
        }
        JSONObject customerData = null;
        if (!clueDetailAddOrSaveClue) {
            customerData = customerEntityExt.getData();
        }
        Integer ifRemind = getIntegerOrDefaultFromFormData(data, CustomerCommunicateEnum.IF_REMIND.getAttr(), BasicConstant.ZERO);
        Integer isPlan = getIntegerOrDefaultFromFormData(data, CustomerCommunicateEnum.ENTER_COMMUNICATE_PLAN.getAttr(), BasicConstant.ZERO);
        // 新建跟进记录中@指定人员
        List<String> atUserIds = saasNeedRedundantAttrPojo.getAtUserIds();
        if (Objects.isNull(atUserIds)) {
            JSONArray jsonArray = data.getJSONArray(CustomerCommunicateEnum.AT_USERNAME.getAttr());
            if (Objects.nonNull(jsonArray)) {
                atUserIds = JSONArray.parseArray(jsonArray.toJSONString(),String.class);
            }
        }
        if (Objects.nonNull(atUserIds) && atUserIds.size() > 0) {
            atUserIds.remove(userId);
            String pushTitle = I18nMessageUtil.getMessage(CommunicatePushConstant.COMMUNICATE_AT_TITLE);
            String customerNameStr;
            String pushContent;
            if (isClue) {
                customerNameStr = FastJsonHelper.getStringOrDefaultFromFormData(data, CommunicateBaseEnum.COMMUNICATE_BUSINESS_HIDE.getAttr(), "");
                pushContent = String.format(I18nMessageUtil.getMessage(CommunicatePushConstant.COMMUNICATE_AT_CONTENT_CLUE), user.getName(), customerNameStr);
            } else {
                customerNameStr = FastJsonHelper.getStringOrDefaultFromFormData(data, CommunicateBaseEnum.MAIN_BUSINESS_HIDE.getAttr(), "");
                pushContent = String.format(I18nMessageUtil.getMessage(CommunicatePushConstant.COMMUNICATE_AT_CONTENT), user.getName(), customerNameStr);
            }
            PushTypeEnum pushTypeEnum = PushTypeEnum.COMMUNICATE_ADD_PUSH;

            PushRefTypePojo.Options options = new PushRefTypePojo.Options(pojoData.getAppId(), pojoData.getMenuId(), pojoData.getFormId(), dataId, Collections.singletonList(dataId), SaasMarkEnum.SAAS.getCode(), pojoData.getBusinessType(), pojoData.getSubBusinessType());
            MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, atUserIds, Collections.singletonList(dataId), 0, null, pushTitle, pushContent, null, options);
            messageService.delayPushDingtalkOAMessage(messageRabbitMqDTO, pushTypeEnum);
        }

        Integer businessType = getIntegerOrDefaultFromFormData(data, CustomerCommunicateEnum.COMMUNICATE_BUSINESS_TYPE.getAttr(), BasicConstant.ZERO);
        if (Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())) {
            Long opportunityId = FastJsonHelper.getLongOrDefaultFromFormData(data, CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getAttr(), 0L);
            if (!Objects.equals(opportunityId, 0L)) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(SalesOpportunityEnum.LAST_CONNECT_TIME.getAttr(), communicateTime);
                UpdateDataEntity updateData = ExplainUtil.getUpdateData(opportunityId, jsonObject, corpid);
                opportunityModel.updateBatch(Collections.singletonList(updateData), corpid);
            }
        }


        JSONObject jsonObject = new JSONObject();
        if (!clueDetailAddOrSaveClue && customerData.getLong(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr()) < communicateTime){
            if (communicateTime > DateTimeUtil.getInt()) {
                communicateTime = DateTimeUtil.getInt();
            }
            Boolean flag = proFormHelp.getSingleRuleList(corpid, RuleSettingEnum.NEW_FOLLOW_UP_RECORD_VISITING_TIME.getConfig(), customerEntityExt.getFormId());
            if (flag) {
                jsonObject.put(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), communicateTime);
            }

        }
        if (jsonObject.size() > 0) {
            UpdateDataEntity updateData = ExplainUtil.getUpdateData(customerId, jsonObject, corpid);
            customerModel.updateBatch(Collections.singletonList(updateData), corpid);

            Long communicateCustomerId = FastJsonHelper.getLongFromFormData(data, CustomerCommunicateEnum.CUSTOMER_NAME.getAttr());
            if (commonHelp.isCustomerPublicPoolSeniorModel(corpid)) {
                transferBackRuleScriptService.deletePublicSeniorTag(corpid, Collections.singletonList(communicateCustomerId), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), customerEntityExt.getFormId());
            } else{
                customerRuleService.deletePublicTag(corpid, Collections.singletonList(communicateCustomerId));
            }
            //评分计算（客户新增，跟进记录）
//            scoreCalculateService.asyncUpdateSingleDataScore(XbbRefTypeEnum.CUSTOMER_MANAGEMENT,corpid,customerId,null);
            DataScoreUpdateSingleDTO dataScoreUpdateBatchDTO = new DataScoreUpdateSingleDTO();
            dataScoreUpdateBatchDTO.setCorpid(corpid);
            dataScoreUpdateBatchDTO.setUserId(workflowTransferPOJO.getUser().getUserId());
            dataScoreUpdateBatchDTO.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
            dataScoreUpdateBatchDTO.setDataId(customerId);
            dataScoreUpdateBatchDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
            scoreCalculateService.updateSingle(dataScoreUpdateBatchDTO);
        }

        // api
        apiHook(workflowTransferPOJO);
        // log
        afterUpdateLog(workflowTransferPOJO);
    }

    @Override
    public void updateBack(Long taskId, WorkflowTransferPOJO workflowTransferPOJO) {
        // 没有审批无需还原
    }

    @Override
    public void approvalFailed(Long taskId, WorkflowTransferPOJO workflowTransferPOJO, Integer taskType) throws XbbException {
        // 没有审批无需处理
    }
}
